import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
import Layout from '@/layout'
import Layout1 from '@/layout/layout'
import el from 'element-ui/src/locale/lang/el'
const _import = require('./router/_import_development')

NProgress.configure({ showSpinner: false }) // NProgress Configuration

var whiteList = ['/login'] // no redirect whitelist
var forPath = '/login'
router.beforeEach(async(to, from, next) => {
  // start progress bar
  urlChange()
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  const hasToken = getToken()
  if (hasToken) {
    if (to.path === forPath) {
      // if is logged in, redirect to the home page
      next({ path: '/index' })

      NProgress.done()
    } else {
      // determine whether the user has obtained his permission roles through getInfo
      const hasRoles = store.getters.name
      if (hasRoles) {
        next()
      } else {
        try {
          // get user info
          // note: roles must be a object array! such as: ['admin'] or ,['developer','editor']
          const { menuList } = await store.dispatch('user/getInfo')
          // generate accessible routes map based on roles
          // asyncRoutesMenu(store.getters.menu)
          // console.log(store.getters.menu)
          // console.log(menuList)
          // const accessRoutes = asyncRoutesMenu(store.getters.menu)
          var newRoutes = isPubAdmin(menuList)

          const accessRoutes = await store.dispatch('permission/generateRoutes', newRoutes)

          //  console.log(accessRoutes);
          // dynamically add accessible routes
          router.addRoutes(accessRoutes)
          // hack method to ensure that addRoutes is complete
          // set the replace: true, so the navigation will not leave a history record
          next({ ...to, replace: true })
        } catch (error) {
          console.log(error)
          // remove token and go to login page to re-login
          await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          // next(`/login?redirect=${to.path}`)
          next({ path: forPath })
          NProgress.done()
        }
      }
    }
  } else {
    /* has no token*/
    // console.log(to.path);
    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      // next(`/login?redirect=${to.path}`)

      next({ path: forPath })
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})

function urlChange() {
  if (window.location.host == 'htadmin.idshanxi.com') {
    console.log(screen.width)
    if (screen.width < 768) { // 768，ipad
      window.location.href = 'https://htadmin.idshanxi.com/mobile/#/'// 去移动端页面
      // this.$router.push({path: "/mobile"});
    } else {
      whiteList = ['/htIndex']
      forPath = '/htIndex'
    }
  } else if (window.location.host == 'idadmin.idshanxi.com') {
    whiteList = ['/login']
    forPath = '/login'
  } else if (window.location.host == 'appadmin.idshanxi.com') {
    whiteList = ['/pubIndex']
    forPath = '/pubIndex'
  } else if (window.location.host == 'ypadmin.idshanxi.com') {
    whiteList = ['/ypIndex']
    forPath = '/ypIndex'
  } else {
    whiteList = ['/pubIndex']// htIndex,  pubIndex, login
    forPath = '/pubIndex'
    console.log(whiteList)
  }
}

function isPubAdmin(route) {
  if (window.location.host == 'appadmin.idshanxi.com' || window.location.host == 'localhost:9529' || window.location.host == '10.10.2.249:9529') {

  } else {
    console.log(route)
    route.forEach((item, index) => {
      if (item.code.indexOf('prevent') !== -1) {
        route.splice(index, 1)
      }
    })
  }
  return route
}

function asyncRoutesMenu(sysResourceMenus) {
  console.log(sysResourceMenus)
  sysResourceMenus.filter(item => {
    if (item.component.indexOf('layout') === -1) {
      if (item.children && item.children.length) {
        item.component = Layout1
      } else {
        item.component = _import(item.component)
      }
    } else {
      // item.path='/nested'

      item.component = Layout
    }
    if (item.children && item.children.length) {
      item.children = asyncRoutesMenu(item.children)
      // commit('asyncRoutes',item.children)
    }
    return true
  })
  // console.log(sysResourceMenus)
  return sysResourceMenus
}
